$(document).ready(function() {
    //表格自适应
    function resizeFnc(){
        var offsetBottom, divWidth;
        divWidth = $("#pmSetListDiv").width();
        offsetBottom =  $(window).height() - $("#pmSetListDiv").offset().top;
        $("#pmSetListDiv").height(offsetBottom * 0.95);
        $("#pmSetListGrd").setGridWidth(divWidth * 0.85);
        $("#pmSetListGrd").setGridHeight(offsetBottom * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });
	var VAL ={
        NORMAL : "0000000"  ,
        EVT_USER : $("#userId").text(),
        T_FBPBISTOL : 'FBPBISTOL',
        T_MTPTOOLPM : 'MTPTOOLPM',
        T_MTPPMITEM : 'MTPPMITEM',
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };

	var domObj = {
		W : $(window),
        $bayIdSel : $("#bayIdSel"),
        $startIn : $("#startIn"),
        $endIn : $("#endIn"),
		$toolRunModeSel : $("#toolRunModeSel"),
		$toolIdSel : $("#toolIdSel"),
		$pmTypeSel : $("#pmTypeSel"),
		
		$PMPlanDialog_titleTxt : $("#PMPlanDialog_titleTxt"),
		$PMPlanDialog_pmDateDatepicker : $("#PMPlanDialog_pmDateDatepicker"),
		$PMPlanDialog_pmEndDateDatepicker : $("#PMPlanDialog_pmEndDateDatepicker"),
        $PMPlanDialog_pmUpdateDate     : $("#PMPlanDialog_pmUpdateDate"),
		$pmUpdateDate : $("#pmUpdateDate"),
		$pmEndDate : $("#pmEndDate"),
		$PMPlanDialog_perCnt : $("#PMPlanDialog_perCnt"),

		$PMPlanDialog_toolIdSel : $("#PMPlanDialog_toolIdSel"),
        $PMPlanDialog_lineIdSel : $("#PMPlanDialog_lineIdSel"),
		$PMPlanDialog_pmTypeSel : $("#PMPlanDialog_pmTypeSel"),
		
		$PMItemDialog_titleTxt : $("#PMItemDialog_titleTxt"),
		$PMItemDialog_pmTypeTxt : $("#PMItemDialog_pmTypeTxt"),
		$PMItemDialog_dataDscTxt : $("#PMItemDialog_dataDscTxt"),
		$PMItemDialog_uSpecTxt : $("#PMItemDialog_uSpecTxt"),
		$PMItemDialog_lSpecTxt : $("#PMItemDialog_lSpecTxt"),
		$PMItemDialog_dataTypeSel : $("#PMItemDialog_dataTypeSel"),
		$PMItemDialog_sampleQtyTxt : $("#PMItemDialog_sampleQtyTxt"),
        $PMItemDialog_toolPmNoteTxt : $("#PMItemDialog_toolPmNoteTxt"),
		buttons : {
			$query_btn : $("#query_btn"),
			$add_btn : $("#add_btn"),
			$import_btn : $("#import_btn"),
			$export_btn : $("#export_btn"),
			$download_btn : $("#download_btn"),
            $select_btn : $("#select_btn"),
            $save_btn : $("#save_btn"),
			$PMPlanDialog_addBtn : $("#PMPlanDialog_addBtn"),
			$PMPlanDialog_saveBtn : $("#PMPlanDialog_saveBtn"),
			$PMPlanDialog_deleteBtn : $("#PMPlanDialog_deleteBtn"),
			$PMPlanDialog_currentBtn : $("#PMPlanDialog_currentBtn"),
			$PMPlanDialog_allBtn : $("#PMPlanDialog_allBtn")
		},
		
        grids:{
            $pmSetListDiv : $("#pmSetListDiv"),
            $pmSetListGrd : $("#pmSetListGrd"),
            $pmSetListPg : $("#pmSetListPg"),
            $pmItemListDiv : $("#pmItemListDiv"),
            $pmItemListGrd : $("#pmItemListGrd"),
            $pmItemListPg : $("#pmItemListPg")
        }
	};
	
	var controlsFunc={
	   	resizeFunc : function(){ 
	    	comResize(domObj.W, domObj.grids.$pmSetListDiv, domObj.grids.$pmSetListGrd);
	    	domObj.grids.$pmItemListGrd.setGridWidth(domObj.W.width()* 0.80);
	    },
    	iniToolRunModeFunc : function(){//初始化设备运行模式
            comAddValueByDataCateFnc("#toolRunModeSel", "TRMD", "data_ext", "data_desc", true);
    	},
        iniBayInfo : function(){//初始化线别
            comAddValueByDataCateFnc("#bayIdSel", "AREA", "data_ext", "data_desc", true);
        },
        iniDateTimePicker1 : function() {

            laydate.render({
                elem: '#startIn',
                type: 'datetime'
            });
            laydate.render({
                elem: '#endIn',
                type: 'datetime'
            });
        },
    	iniToolIdFunc : function(){//初始化设备代码
    		var inTrxObj = {
				trx_id     : VAL.T_FBPBISTOL ,
				action_flg : 'H',
				evt_user   : VAL.EVT_USER,
				iary       : [{
					tool_run_mode : $.trim(domObj.$toolRunModeSel.val())
                }]
    		};

    		var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
    		if( outTrxObj.rtn_code == _NORMAL ) {
    			SelectDom.addSelectArr(domObj.$toolIdSel, outTrxObj.oary, "tool_id","tool_dsc",true, true);
    		}
    	},
    	iniPmTypeFunc : function(){
    		var modelId = $.trim(domObj.$toolRunModeSel.val());
    		var toolId = $.trim(domObj.$toolIdSel.val());
    		if(toolId){
    	        var inTrxObj = {
    	 				trx_id     : VAL.T_MTPPMITEM ,
    	 				action_flg : 'T'        ,
    	 				tool_id    : toolId
    	 		};
    	 		var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    	 		if( outTrxObj.rtn_code == _NORMAL ) {
    	 			SelectDom.addSelectArr(domObj.$pmTypeSel, outTrxObj.oaryA, "pm_type_fk","pm_type_dsc",true, true);
    	 		}
    		}else if(modelId){
    			var inTrxObj = {
    	 				trx_id     : VAL.T_MTPPMITEM ,
    	 				action_flg : 'T'        ,
    	 				tool_model_fk : modelId
    	 		};
    	 		var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    	 		if( outTrxObj.rtn_code == _NORMAL ) {
    	 			SelectDom.addSelectArr(domObj.$pmTypeSel, outTrxObj.oaryA, "pm_type_fk","pm_type_dsc",true, true);
    	 		}
    		}else{
        		comAddValueByDataCateFnc("#pmTypeSel", "PMTP", "ext_1", "data_desc", true);
    		}
    	},
        //初始化班别
        initShiftIdSel : function (){
            comAddValueByDataCateFnc("#shift_id_fk","SHIF","data_id","data_desc",true,false);
        },
	    //初始化工艺确认flg
		initTechConfirmFlg : function () {
                $("#tech_confirm_flg").empty();
                $("#tech_confirm_flg").append("<option value="+"Y"+">"+"Y" +"</option>");
                $("#tech_confirm_flg").append("<option value="+"N"+">"+"N" +"</option>");
                $("#tech_confirm_flg").select2({
                    theme : "bootstrap"
                });
		},
	    //初始化生产确认flag
		initProdConfirmFlg : function () {
            $("#prod_confirm_flg").empty();
            $("#prod_confirm_flg").append("<option value="+"Y"+">"+"Y" +"</option>");
            $("#prod_confirm_flg").append("<option value="+"N"+">"+"N" +"</option>");
            $("#prod_confirm_flg").select2({
                theme : "bootstrap"
            });
        },
	    /**
    	 * 增加修改和删除按钮
    	 * 说明:(1) addGridButton :在Grid中添加了两个Button: "修改" , "删除"
    	 *     (2) modifyFnc     :点击修改时,调用此函数.
    	 *     (3) deleteFnc     :点击删除时,调用此函数.
    	 */
    	addGridButton : function(){
    		var ids = domObj.grids.$pmSetListGrd.jqGrid('getDataIDs');
    		for(var i=0; i<ids.length; i++){
    			var id=ids[i];   
    			var modify = "<button id=" + "'Mod" + ids[i] + "'" + " style='color:#f60'>修改/删除</button>";  
    			domObj.grids.$pmSetListGrd.jqGrid('setRowData', ids[i], { modifyItem: modify});
    			$("#Mod" + ids[i]).click( controlsFunc.modifyFunc );
    		}  
    	},
    	modifyFunc : function(){
    		domObj.buttons.$PMPlanDialog_saveBtn.data("action_flg","U");
    		controlsFunc.iniDialogFunc(this.id.substr(3));
    		return false;
    	},
    	/***************************初始化保养计划Dialog***************************/
    	iniDialogFunc : function(id){
		      /*****
	        当多次弹出对话框的同时也会多次绑定click事件。
	        解决办法: 在show Dialog时将click unbind全部掉
	                  然后再绑定，这样就只剩下一个click事件了。
	      **********/
    		var action_flg = domObj.buttons.$PMPlanDialog_saveBtn.data("action_flg");
		    $("#PMPlanDialog").unbind('shown.bs.modal');
		    domObj.buttons.$PMPlanDialog_saveBtn.unbind('click');
		    domObj.buttons.$PMPlanDialog_deleteBtn.unbind('click');
		    controlsFunc.iniDateTimePicker();
	  		domObj.$PMPlanDialog_titleTxt.text("");
	  		domObj.$PMPlanDialog_perCnt.text("");
	  		$("#PMPlanDialog_pmSeqIdSpan").text("");
	  		domObj.buttons.$PMPlanDialog_currentBtn.attr("checked","checked");
	  		if(action_flg == "A"){
	  			domObj.$PMPlanDialog_titleTxt.text("新增保养计划");
                $("#nowPmDate").attr("style","display:none;");//将当前保养开始日期隐藏
                $("#endPmDate").attr("style","display:none;");//将当前保养结束日期隐藏
	  			domObj.buttons.$PMPlanDialog_deleteBtn.hide();
	  			domObj.$PMPlanDialog_toolIdSel.attr(VAL.ENABLED_ATTR);
	  			domObj.$PMPlanDialog_pmTypeSel.attr(VAL.ENABLED_ATTR);
	  			domObj.$PMPlanDialog_lineIdSel.attr(VAL.ENABLED_ATTR);
				controlsFunc.iniDialogToolIdFunc();
				controlsFunc.iniDialogPmTypeFunc();
				controlsFunc.initLineListFnc();
				controlsFunc.initShiftIdSel();
				controlsFunc.initTechConfirmFlg();
				controlsFunc.initProdConfirmFlg();
	  		}else{
	  			domObj.$PMPlanDialog_titleTxt.text("修改/删除保养计划");
                $("#nowPmDate").attr("style","display:show();");//将当前保养开始日期显示
                $("#nowPmShiftIdFk").attr("style","display:show();");//将当前班别显示
	  			domObj.buttons.$PMPlanDialog_deleteBtn.show();
	  			domObj.$PMPlanDialog_toolIdSel.attr(VAL.DISABLED_ATTR);
	  			domObj.$PMPlanDialog_lineIdSel .attr(VAL.DISABLED_ATTR);
	  			domObj.$PMPlanDialog_pmTypeSel.attr(VAL.DISABLED_ATTR);
	  			$("#PMPlanDialog_dataCateForm select").empty();
	      		var rowData  = domObj.grids.$pmSetListGrd.jqGrid("getRowData",id);
                domObj.$PMPlanDialog_pmDateDatepicker.val(rowData.from_date);
                $("#nowPmShift_id_fk").val(rowData.shift_id_fk);
                // domObj.$PMPlanDialog_pmEndDateDatepicker.val(rowData.end_date);
                domObj.$PMPlanDialog_perCnt.val(rowData.pm_person_cnt);
                $("#plan_duration").val(rowData.plan_duration);
                $("#maintenance_master").val(rowData.maintenance_master);
	  			$("#PMPlanDialog_pmSeqIdSpan").text(rowData.pm_seq_id);
	      		domObj.$PMPlanDialog_toolIdSel.append("<option value='" + rowData.tool_id_fk + "' >" + rowData.tool_id_fk + "</option>");
	      		domObj.$PMPlanDialog_pmTypeSel.append("<option value='" + rowData.pm_type_fk + "' >" + rowData.pm_type_dsc + "</option>");
                domObj.$PMPlanDialog_lineIdSel.append("<option value='" + rowData.line_id_fk + "' >" + rowData.line_id_fk + "</option>");
                controlsFunc.initShiftIdSel();
                controlsFunc.initTechConfirmFlg();
                controlsFunc.initProdConfirmFlg();
                SelectDom.setSelect($("#shift_id_fk"),rowData.shift_id_fk,rowData.shift_id_fk);
                SelectDom.setSelect($("#tech_confirm_flg"),rowData.tech_confirm_flg,rowData.tech_confirm_flg);
                SelectDom.setSelect($("#prod_confirm_flg"),rowData.prod_confirm_flg,rowData.prod_confirm_flg);
	      		//选中保养计划已经设定保养项目
	      		controlsFunc.iniPlanItemFunc();
	  		}

      		$("#PMPlanDialog_dataCateForm select").select2({
    			theme : "bootstrap",
    	        width : domObj.W.width()* 0.12
    	    });
      		domObj.buttons.$PMPlanDialog_saveBtn.bind('click', btnFunc.dialogSaveFunc);
      		domObj.buttons.$PMPlanDialog_deleteBtn.bind('click', btnFunc.dialogDeleteFunc);
		    $("#PMPlanDialog").modal('show');
    	},
		iniDateTimePicker : function() {
            laydate.render({
                elem: '#pmUpdateDate',
                type: 'date'
            });
            // laydate.render({
            //     elem: '#pmEndDate',
            //     type: 'datetime'
            // });
        },

    	iniDialogToolIdFunc : function(){//初始化设备代码
            // $("#toolIDSel").empty();
            // var fabId =  $.trim($("#fabIdSel").val());
            var lineId =   $.trim($("#PMPlanDialog_lineIdSel").val());
            // var opeId = $.trim($("#opeIDSel").val());
            // var opeVer = '00000';
            var iary2  = {
                // fab_id_fk : fabId,
                bay_id :lineId,
                // ope_id_fk : opeId,
                // ope_ver : opeVer
            }
            var inObj2 = {
                trx_id : VAL.T_FBPBISTOL,
                action_flg : "Q",
                iary : [iary2]
            };
            var outObj2 = comTrxSubSendPostJson(inObj2);
            if(outObj2.rtn_code === "0000000"){
                SelectDom.addSelectArr(domObj.$PMPlanDialog_toolIdSel,outObj2.oary,["tool_id"],["tool_dsc"],"Y",true,false);
            }
    		// var inTrxObj = {
				// trx_id     : VAL.T_FBPBISTOL ,
				// action_flg : 'L'
    		// };
    		// var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
    		// if( outTrxObj.rtn_code == _NORMAL ) {
    		// 	SelectDom.addSelectArr(domObj.$PMPlanDialog_toolIdSel, outTrxObj.oary, "tool_id","tool_dsc",true, true);
        		// domObj.$PMPlanDialog_toolIdSel.select2({
        		// 	theme : "bootstrap",
        	 //        width : domObj.W.width()* 0.12
        	 //    });
    		// }
    	},

        initLineListFnc : function(){
        comAddValueByDataCateFnc("#PMPlanDialog_lineIdSel","AREA","data_ext","data_desc",true,false);
    	},

    	iniDialogPmTypeFunc : function(){
			domObj.$PMPlanDialog_pmTypeSel.empty();
			domObj.grids.$pmItemListGrd.jqGrid("clearGridData");
    		var toolId = $.trim(domObj.$PMPlanDialog_toolIdSel.val());
    		if(toolId){
    	        var inTrxObj = {
    	 				trx_id     : VAL.T_MTPPMITEM ,
    	 				action_flg : 'T'        ,
    	 				tool_id    : toolId
    	 		};
    	 		var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    	 		if( outTrxObj.rtn_code == _NORMAL ) {
    	 			SelectDom.addSelectArr(domObj.$PMPlanDialog_pmTypeSel, outTrxObj.oaryA, "pm_type_fk","pm_type_dsc",true, true);
    	 		}
    		}
    		domObj.$PMPlanDialog_pmTypeSel.select2({
    			theme : "bootstrap",
    	        width : domObj.W.width()* 0.12
    	    });
    	},
    	iniPlanItemFunc : function(){
            var pm_date = $.trim(domObj.$PMPlanDialog_pmDateDatepicker.val());
			var shift_id_fk = $.trim($("#shift_id_fk").val());
			if(shift_id_fk == "D"){
                pm_date = pm_date +" 08:00:00";
			}else if (shift_id_fk == "N"){
                pm_date = pm_date +" 20:00:00";
			}
			var tool_id = $.trim(domObj.$PMPlanDialog_toolIdSel.val());
			var pm_type = $.trim(domObj.$PMPlanDialog_pmTypeSel.val());
			if(!pm_date || !tool_id || !pm_type){
				domObj.grids.$pmItemListGrd.jqGrid("clearGridData");
				return false;
			}
			var inTrxObj = {
	            trx_id        : VAL.T_MTPTOOLPM ,
	            action_flg    : 'I'        ,
	            tool_id_fk : tool_id,
	            pm_type    : pm_type,
	            from_date  : pm_date,
	        };
	        
	        var outTrxObj = comTrxSubSendPostJson(inTrxObj);
	        if( outTrxObj.rtn_code == _NORMAL ) {
	        	setGridInfo(outTrxObj.oaryB, "#pmItemListGrd");
	        	controlsFunc.addDialogGridButton();
	        }else{
	        	domObj.grids.$pmItemListGrd.jqGrid("clearGridData");
	        }
    	},
    	addDialogGridButton : function(){
    		var ids = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
    		for(var i=0; i<ids.length; i++){
    			var id=ids[i];   
    			var modify = "<button id=" + "'mod" + ids[i] + "'" + " style='color:#f60'>修改</button>";  
    			var deleteItem = "<button id=" + "'del" + ids[i] + "'" + " style='color:#f60'>删除</button>";  
    			domObj.grids.$pmItemListGrd.jqGrid('setRowData', ids[i], { modifyItem: modify,deleteItem:deleteItem});
    			$("#mod" + ids[i]).click( controlsFunc.dialogModifyFunc );
    			$("#del" + ids[i]).click( controlsFunc.dialogDeleteFunc );
    		}  
    	},
    	dialogModifyFunc : function(){
    		controlsFunc.iniItemDialogFunc("U", this.id.substr(3));
    		return false;
    	},
    	dialogDeleteFunc : function(){
    		var obj = this ;
    		domObj.buttons.$query_btn.showCallBackWarnningDialog({
    			errMsg  : "是否删除保养项目,请确认!!!!",
    			callbackFn : function(data) {
    				if(data.result==true){
    					domObj.grids.$pmItemListGrd.jqGrid("delRowData",obj.id.substr(3));
    				}
    			}
    		});
    		return false ;
    	},
    	/***************************初始化保养项目Dialog***************************/
    	iniItemDialogFunc : function(action_flg, id){
		      /*****
	        当多次弹出对话框的同时也会多次绑定click事件。
	        解决办法: 在show Dialog时将click unbind全部掉
	                  然后再绑定，这样就只剩下一个click事件了。
	      **********/
		    $("#PMItemDialog").unbind('shown.bs.modal');
		    $("#PMItemDialog_saveBtn").unbind('click');
		    
	  		domObj.$PMItemDialog_titleTxt.text("");
	  		$("#PMItemDialog_dataCateForm input").val("");
	  		domObj.$PMItemDialog_pmTypeTxt.attr(VAL.DISABLED_ATTR);
	  		if(action_flg == "A"){
	  			domObj.$PMItemDialog_titleTxt.text("新增保养项目");
	  			domObj.$PMItemDialog_dataDscTxt.attr(VAL.ENABLED_ATTR);
	  		}else{
	  			domObj.$PMItemDialog_titleTxt.text("修改保养项目");
	  			domObj.$PMItemDialog_dataDscTxt.attr(VAL.DISABLED_ATTR);
	  		}
  		
    		domObj.$PMItemDialog_dataTypeSel.select2({
    			theme : "bootstrap",
    	        width : domObj.W.width()* 0.1755
    	    });
    		
	  		var pm_type = $.trim(domObj.$PMPlanDialog_pmTypeSel.val());
	  		if(!pm_type){
	  			showErrorDialog("","保养类型不能为空！");
	  			return false;
	  		}else{
	  			domObj.$PMItemDialog_pmTypeTxt.val(pm_type);
	  		}
	  		
	  		if(action_flg == "U"){
	      		var rowData  = domObj.grids.$pmItemListGrd.jqGrid("getRowData",id);
	  			domObj.$PMItemDialog_dataDscTxt.val(rowData.data_dsc);
	  			domObj.$PMItemDialog_uSpecTxt.val(rowData.u_spec);
	  			domObj.$PMItemDialog_lSpecTxt.val(rowData.l_spec);
	  			domObj.$PMItemDialog_dataTypeSel.val(rowData.data_typ).trigger("change");
	  			domObj.$PMItemDialog_sampleQtyTxt.val(rowData.data_cnt);
	  			domObj.$PMItemDialog_toolPmNoteTxt.val(rowData.pm_note);
	  		}
  		
		    $("#PMItemDialog_saveBtn").bind('click',{action_flg : action_flg, id:id}, btnFunc.itemDialogSaveFunc);
		    $("#PMItemDialog").modal('show');
    	}	
	};
	
	var btnFunc = {
		queryFunc : function(){//查询设备对应的保养计划
            var startTime = $.trim(domObj.$startIn.val());
            var endTime = $.trim(domObj.$endIn.val());
			var pmTypeId = $.trim(domObj.$pmTypeSel.val());
			var modelId = $.trim(domObj.$toolRunModeSel.val());
			var toolId = $.trim(domObj.$toolIdSel.val());
			var bayIdSel= $.trim(domObj.$bayIdSel.val());

			var inTrxObj = {
	 				trx_id     : VAL.T_MTPTOOLPM ,
	 				action_flg : 'F'        ,
	 				evt_usr    : VAL.EVT_USER
	 		};
			
			if(pmTypeId){
				inTrxObj.pm_type = pmTypeId;
			}
			
			if(modelId){
				inTrxObj.tool_model = modelId;
			}
			if(bayIdSel){
				inTrxObj.bayIdSel=bayIdSel;
			}
			
			if(startTime){
				inTrxObj.pm_start_time = startTime;
			}
            if(endTime){
                inTrxObj.pm_end_time = endTime;
            }
	 		var outTrxObj = comTrxSubSendPostJson(inTrxObj);
	 		if( outTrxObj.rtn_code == _NORMAL ) {
	 			setGridInfo(outTrxObj.oaryA,"#pmSetListGrd");
	 			controlsFunc.addGridButton();
	 		}
		},
		addFunc : function(){
			domObj.buttons.$PMPlanDialog_saveBtn.data("action_flg","A");
		    controlsFunc.iniDialogFunc();
		},
		//保养计划Dialog中查询设备对应保养类型的保养项目
		dialogQueryItemFunc : function(){
			var tool_id = $.trim(domObj.$PMPlanDialog_toolIdSel.val());
			var pm_type = $.trim(domObj.$PMPlanDialog_pmTypeSel.val());
			if(!tool_id || !pm_type){
				domObj.grids.$pmItemListGrd.jqGrid("clearGridData");
				return false;
			}
			var inTrxObj = {
	            trx_id        : VAL.T_MTPPMITEM ,
	            action_flg    : 'Q'        ,
	            tool_id       : tool_id,
	            pm_type       : pm_type
	        };
	        
	        var outTrxObj = comTrxSubSendPostJson(inTrxObj);
	        if( outTrxObj.rtn_code == _NORMAL ) {
	        	setGridInfo(outTrxObj.oaryA, "#pmItemListGrd");
	        	controlsFunc.addDialogGridButton();
	        }
		},
		//保养计划Dialog保存按钮
		dialogSaveFunc : function(){
			var iaryA = new Array();
			var action_flg = domObj.buttons.$PMPlanDialog_saveBtn.data("action_flg");

			var tool_id = $.trim(domObj.$PMPlanDialog_toolIdSel.val());
			var pm_type = $.trim(domObj.$PMPlanDialog_pmTypeSel.val());
			var maintenance_master = $.trim($("#maintenance_master").val());
			var line_id_fk = $.trim(domObj.$PMPlanDialog_lineIdSel.val());
			var shift_id_fk = $.trim($("#shift_id_fk").val());
			var tech_confirm_flg = $.trim($("#tech_confirm_flg").val());
			var prod_confirm_flg = $.trim($("#prod_confirm_flg").val());
			var plan_duration = $.trim($("#plan_duration").val());
            if(action_flg=="A"){//添加
               var pm_date_start = $.trim(domObj.$pmUpdateDate.val());
               // var pm_date_end   = $.trim(domObj.$pmEndDate.val());
                if(!pm_date_start){
                    showErrorDialog("", "保养计划开始日期不能为空！");
                    return false;
                }
            }else {//修改
               var pm_date_start = $.trim(domObj.$pmUpdateDate.val());
               // var pm_date_end   = $.trim(domObj.$pmEndDate.val());
               var pm_old_start = $.trim(domObj.$PMPlanDialog_pmDateDatepicker.val());
               var old_shift_id_fk = $.trim($("#nowPmShift_id_fk").val());
            }
			
			if(!tool_id){
				showErrorDialog("", "设备代码不能为空！");
				return false;
			}
			
			if(!pm_type){
				showErrorDialog("", "保养类型不能为空！");
				return false;
			}
			if(!maintenance_master){
                showErrorDialog("", "保养主负责人不能为空！");
                return false;
			}
			if(!shift_id_fk){
                showErrorDialog("", "班别不能为空！");
                return false;
			}
			if(!tech_confirm_flg){
                showErrorDialog("", "工艺是否确认标识不能为空！");
                return false;
			}
            if(!prod_confirm_flg){
                showErrorDialog("", "生产是否确认标识不能为空！");
                return false;
            }

			var rowCnt = domObj.grids.$pmItemListGrd.jqGrid("getGridParam","reccount");
			if(rowCnt<=0){
			    showErrorDialog("","保养项目不能为空，请添加保养项目！");
			    return false;
			}
			var rowIDs = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
			for(var i=0;i<rowIDs.length;i++){
				var rowData = domObj.grids.$pmItemListGrd.jqGrid("getRowData",rowIDs[i]);
				iaryA.push({
					data_dsc    : rowData['data_dsc'],
					u_spec      : rowData['u_spec'],
					l_spec      : rowData['l_spec'],
					data_typ    : rowData['data_typ'],
					pm_note     : rowData['pm_note'],
					data_cnt    : parseInt(rowData['data_cnt'],10)
				});
	        }
			
			var change_typ = "A";
			if(domObj.buttons.$PMPlanDialog_currentBtn.attr("checked") == "checked"){
				change_typ = "C";
			}
			
			var inTrxObj ={
      			  trx_id     : VAL.T_MTPTOOLPM,
      			  action_flg : action_flg,
      			  tool_id_fk : tool_id,
      			  pm_type    : pm_type,
      			  from_date  : pm_old_start,
                  old_shift_id_fk : old_shift_id_fk,
                  pm_start_time: pm_date_start,
				  maintenance_master : maintenance_master,
                  shift_id_fk : shift_id_fk,
                  tech_confirm_flg : tech_confirm_flg,
                  prod_confirm_flg : prod_confirm_flg,
      			  change_typ : change_typ,
      			  line_id_fk : line_id_fk,
                  plan_duration: plan_duration,
      			  pm_seq_id  : $.trim($("#PMPlanDialog_pmSeqIdSpan").text()),
      			  evt_usr    : VAL.EVT_USER,
      			  iaryA      : iaryA
    		};
			
			var outTrxObj = comTrxSubSendPostJson(inTrxObj);
			if( outTrxObj.rtn_code == _NORMAL ) {
				showSuccessDialog("[" + tool_id + "][" + pm_type + "]保养计划保存成功");
				btnFunc.queryFunc();
			}
			
//			$("#PMPlanDialog").modal('hide');
		},

		//TODO 保存excel导入的保养计划
		saveExcelFunc : function(){
            var action_flg = "N";
            var rowIDs = domObj.grids.$pmSetListGrd.jqGrid('getDataIDs');
            var iaryBList = [];
            for(var i=0;i<rowIDs.length;i++){
                var rowData = domObj.grids.$pmSetListGrd.jqGrid("getRowData",rowIDs[i]);
                if(!rowData.from_date){
                    showErrorDialog("", "保养计划开始日期不能为空！");
                    return false;
				}

                if(!rowData.tool_id_fk){
                    showErrorDialog("", "设备代码不能为空！");
                    return false;
				}
                if(!rowData.pm_type_fk){
                    showErrorDialog("", "保养类型不能为空！");
                    return false;
                }
                if(!rowData.maintenance_master){
                    showErrorDialog("", "保养主负责人不能为空！");
                    return false;
                }
                if(!rowData.shift_id_fk){
                    showErrorDialog("", "班别不能为空！");
                    return false;
                }
                if(!rowData.tech_confirm_flg){
                    showErrorDialog("", "工艺是否确认标识不能为空！");
                    return false;
                }
                if(!rowData.prod_confirm_flg){
                    showErrorDialog("", "生产是否确认标识不能为空！");
                    return false;
                }

                var pm_date_start = rowData.from_date;
                var line_id_fk = rowData.line_id_fk;
                var tool_id = rowData.tool_id_fk;
                var pm_type = rowData.pm_type_fk;
                var shift_id_fk = rowData.shift_id_fk;
                var maintenance_master = rowData.maintenance_master;
                var plan_duration =  rowData.plan_duration;
                var tech_confirm_flg = rowData.tech_confirm_flg;
                var prod_confirm_flg = rowData.prod_confirm_flg;
                var change_typ = "C";

                var iaryB ={
                    pm_start_time: pm_date_start,
                    line_id_fk : line_id_fk,
                    tool_id_fk : tool_id,
                    pm_type    : pm_type,
                   	shift_id_fk : shift_id_fk,
                    maintenance_master : maintenance_master,
                    plan_duration : plan_duration,
                    tech_confirm_flg : tech_confirm_flg,
                    prod_confirm_flg : prod_confirm_flg,
                    change_typ : change_typ,

				};
                iaryBList.push(iaryB);
            }

            var inTrxObj ={
                trx_id     : VAL.T_MTPTOOLPM,
                action_flg : action_flg,
                evt_usr    : VAL.EVT_USER,
                iaryB      : iaryBList
            };

            var outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if( outTrxObj.rtn_code == _NORMAL ) {
                showSuccessDialog("[" + tool_id + "][" + pm_type + "]保养计划保存成功");
                btnFunc.queryFunc();
            }

		},

		//保养计划删除
		dialogDeleteFunc : function(){
			var iaryA = new Array();
			/*var pm_date = $.trim(domObj.$PMPlanDialog_pmDateDatepicker.data("datetimepicker").getLocalDate().format('yyyy-MM-dd'));*/
            var pm_old_start = $.trim(domObj.$PMPlanDialog_pmDateDatepicker.val());
            var pm_old_end = $.trim(domObj.$PMPlanDialog_pmEndDateDatepicker.val());
			var tool_id = $.trim(domObj.$PMPlanDialog_toolIdSel.val());
			var pm_type = $.trim(domObj.$PMPlanDialog_pmTypeSel.val());
			var shift_id_fk = $.trim($("#nowPmShift_id_fk").val());
			if(!pm_old_start){
				showErrorDialog("", "保养计划开始日期不能为空！");
				return true;
			}

            // if(!pm_old_end){
            //     showErrorDialog("", "保养计划结束日期不能为空！");
            //     return true;
            // }
			
			if(!tool_id){
				showErrorDialog("", "设备代码不能为空！");
				return true;
			}
			
			if(!pm_type){
				showErrorDialog("", "保养类型不能为空！");
				return true;
			}
			if(domObj.buttons.$PMPlanDialog_currentBtn.attr("checked") == "checked"){
				var change_typ = "C";
			}else{
				var change_typ = "A";
			}
			var inTrxObj ={
      			  trx_id     : VAL.T_MTPTOOLPM,
      			  action_flg : 'D',
      			  tool_id_fk : tool_id,
      			  pm_type    : pm_type,
      			  from_date  : pm_old_start,
      			  end_date : pm_old_end,
      			  change_typ : change_typ,
				  shift_id_fk : shift_id_fk,
      			  pm_seq_id  : $.trim($("#PMPlanDialog_pmSeqIdSpan").text()),
      			  evt_usr    : VAL.EVT_USER
    		};
			
			var outTrxObj = comTrxSubSendPostJson(inTrxObj);
			if( outTrxObj.rtn_code == _NORMAL ) {
				showSuccessDialog("[" + tool_id + "][" + pm_type + "]保养计划删除成功");
				btnFunc.queryFunc();
			}
			$("#PMPlanDialog").modal('hide');
		},
		//保养项目Dialog保存按钮
		itemDialogSaveFunc : function(e){
			var rowData = new Array();
			var pm_type = $.trim(domObj.$PMItemDialog_pmTypeTxt.val());
			if(!pm_type){
				showErrorDialog("","请输入保养类型！");
				return false;
			}
			
			var data_dsc = $.trim(domObj.$PMItemDialog_dataDscTxt.val());
			if(!data_dsc){
				showErrorDialog("","请输入保养项目名称！");
				return false;
			}
			
			/**
			 * 检查数据格式
			 */
			var u_spec = $.trim(domObj.$PMItemDialog_uSpecTxt.val());
			if(u_spec && !ComRegex.isNumber(u_spec)){
				showErrorDialog("","上规格不是有效的数字");
				return false;
			}
			var l_spec = $.trim(domObj.$PMItemDialog_lSpecTxt.val());
			if(l_spec && !ComRegex.isNumber(l_spec)){
				showErrorDialog("","下规格不是有效的数字");
				return false;
			}
			
			if(u_spec && l_spec && parseFloat(u_spec,10) < parseFloat(l_spec,10)){
				showErrorDialog("","上规格不能小于下规格");
				return false;
			}
			
			var data_typ = $.trim(domObj.$PMItemDialog_dataTypeSel.val());
			if(!data_typ){
				showErrorDialog("","请选择数据类型！");
				return false;
			}
			
			var data_cnt = $.trim(domObj.$PMItemDialog_sampleQtyTxt.val());
            if(!ComRegex.isInt(data_cnt)){
                showErrorDialog("","样本数量不是有效的数字");
                return false;
            }
            var pm_note=$.trim(domObj.$PMItemDialog_toolPmNoteTxt.val());
			/*if(!data_cnt){
				data_cnt = 1;
			}else if(!ComRegex.isInt(data_cnt)){
				showErrorDialog("","样本数量不是有效的数字");
				return false;
			}*/
			
			rowData.push({
				pm_type_fk  : pm_type,
				data_dsc    : data_dsc,
				u_spec      : u_spec,
				l_spec      : l_spec,
				data_typ    : data_typ,
				pm_note     :  pm_note,
				data_cnt    : parseInt(data_cnt)
			});
			if(e.data.action_flg == "U"){
				domObj.grids.$pmItemListGrd.jqGrid("setRowData", e.data.id, rowData[0]);
			}else{
				//新增时检查保养类型和保养项目是否已经存在
				var rowIDs = domObj.grids.$pmItemListGrd.jqGrid('getDataIDs');
				for(var i=0;i<rowIDs.length;i++){
					var rowdata = domObj.grids.$pmItemListGrd.jqGrid("getRowData",rowIDs[i]);
					if(rowdata['pm_type_fk'] == pm_type && rowdata['data_dsc'] == data_dsc){
						showErrorDialog("","此保养类型、保养项目列表中已经存在，请确认！");
						return false;
					}
		        }
				
				var newRowId = getGridNewRowID("#pmItemListGrd");
				domObj.grids.$pmItemListGrd.jqGrid("addRowData", newRowId, rowData[0]);
				controlsFunc.addDialogGridButton();
			}
			$("#PMItemDialog").modal('hide');
		},

        selectFileFunc  :function(){
            domObj.buttons.$select_btn.click();
        },

        downloadTempFun: function () {
            if ($("#downForm").length > 0) {
                $("#downForm").remove();
            }
            var str = '<form id="downForm" action="download.do" method="post">';
            str = str + '<input type="hidden" name="fileName" id= "fileName" />';
            str = str + "</form>";
            $(str).appendTo("body");
            $("#fileName").val("3720.xlsx");
            $("#downForm").submit();
        },

        uploadFnc : function(obj){
            //清空jqgrid里面的数据
            domObj.grids.$pmSetListGrd.jqGrid("clearGridData")
			/*
			 FileReader共有4种读取方法：
			 1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
			 2.readAsBinaryString(file)：将文件读取为二进制字符串
			 3.readAsDataURL(file)：将文件读取为Data URL
			 4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
			 */
            var wb;//读取完成的数据
            var rABS = true; //是否将文件读取为二进制字符串
            if(!obj.files) {
                return;
            }
            var fileName = obj.value;
            if(fileName.length > 1 && fileName ) {
                var ldot = fileName.lastIndexOf(".");
                var type = fileName.substring(ldot + 1);
                if(!(type=="xlsx"||type=="xls")) {
                    showErrorDialog("", "只能导入excel文件");
                    return;
                }
            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = e.target.result;
                if(rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                var data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                data = JSON.parse(JSON.stringify(data).replace(/保养开始时间/g,"date"));
                data = JSON.parse(JSON.stringify(data).replace(/线别/g,"line_id_fk"));
                data = JSON.parse(JSON.stringify(data).replace(/设备代码/g,"tool_id_fk"));
                data = JSON.parse(JSON.stringify(data).replace(/保养类型/g,"pm_type_fk"));
                data = JSON.parse(JSON.stringify(data).replace(/班别/g,"shift_id_fk"));
                data = JSON.parse(JSON.stringify(data).replace(/保养主负责人/g,"maintenance_master"));
                data = JSON.parse(JSON.stringify(data).replace(/计划时长/g,"plan_duration"));
                data = JSON.parse(JSON.stringify(data).replace(/是否需要工艺确认/g,"tech_confirm_flg"));
                data = JSON.parse(JSON.stringify(data).replace(/是否需要生产确认/g,"prod_confirm_flg"));
				for(var i = 0; i < data.length; i++){
					var dataValue = data[i];
					var from_date = dataValue.date.replace(/\//g,"-");
					data[i].from_date = from_date;
				}
                setGridInfo(data, domObj.grids.$pmSetListGrd);
                controlsFunc.addGridButton();
            };
            if(rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
            function fixdata(data) { //文件流转BinaryString
                var o = "", l = 0, w = 10240;
                for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            }
        },
        exportFunc : function(){
            exportExcel("#pmSetListGrd");
        },

	};

    function iniGridInfo() {
    	var pmSetListInfoCM = [
    	    {name: 'modifyItem'   , index: 'modifyItem'    , label: "修改/删除"    , sortable: false  ,width: 100 },
     	    {name: 'from_date'      , index: 'from_date'     , label: "保养开始日期"     , sortable: false  ,width: 220 },
     	    // {name: 'end_date'      , index: 'end_date'     , label: "保养结束日期"     , sortable: false  ,width: 220 },
     	    {name: 'line_id_fk'      , index: 'line_id_fk'     , label: "线别"     , sortable: false  ,width: 220 },
     	    {name: 'tool_id_fk'     , index: 'tool_id_fk'    , label: TOOL_ID_TAG     , sortable: false  ,width: 220 },
     	    {name: 'tool_model'     , index: 'tool_model'    , label: TOOL_RUN_MODEL_TAG  , sortable: false  ,width: 170 },
     	    {name: 'pm_type_fk'     , index: 'pm_type_fk'    , label: PM_TYPE_TAG      , sortable: false  ,width: 170 },
     	    {name: 'pm_type_dsc'    , index: 'pm_type_dsc'   , label: PM_TYPE_DSC_TAG      , sortable: false  ,width: 170 },
     	    {name: 'shift_id_fk'    , index: 'shift_id_fk'   , label: "班别"      , sortable: false  ,width: 170 },
     	    {name: 'maintenance_master'    , index: 'maintenance_master'   , label: "保养主负责人"      , sortable: false  ,width: 170 },
     	    {name: 'plan_duration'    , index: 'plan_duration'   , label: "计划时长"      , sortable: false  ,width: 170 },
     	    {name: 'tech_confirm_flg'    , index: 'tech_confirm_flg'   , label: "是否需要工艺确认"      , sortable: false  ,width: 170 },
     	    {name: 'prod_confirm_flg'    , index: 'prod_confirm_flg'   , label: "是否需要生产确认"      , sortable: false  ,width: 170 },
     	    {name: 'pm_seq_id'      , index: 'pm_seq_id'     , label: ""        , sortable: false  ,width: 1, hidden:true },
     	    {name: 'evt_seq_id'     , index: 'evt_seq_id'     , label: ""        , sortable: false  ,width: 1, hidden:true }
     	];
     	domObj.grids.$pmSetListGrd.jqGrid({
     		  url:"",
     	      datatype:"local",
     	      mtype:"POST",
     	      autowidth:true,//宽度根据父元素自适应
            shrinkToFit:false,
            autoScroll: false,
     	      scroll:false,
     	      resizable : true,
     	      loadonce:true,
     	      fixed: true,
     	      viewrecords : true, //显示总记录数
     	      pager : '#pmSetListPg',
     	      rownumbers  :true ,//显示行号
     	      pginput  : false ,
     	      rownumWidth : 20,  //行号列宽度
     	      emptyrecords :true ,
     	      colModel: pmSetListInfoCM
     	});
    	var measureItemListInfoCM = [
     	    {name: 'modifyItem'   , index: 'modifyItem'    , label: MODIFY_BTN_TAG,     sortable: false  ,width: 50 },
      	    {name: 'deleteItem'   , index: 'deleteItem'    , label: DELETE_BTN_TAG , sortable: false  ,width: 50 },
      	    {name: 'pm_type_fk'      , index: 'pm_type_fk'     , label: "保养类型"       , sortable: false  ,width: 140 },
      	    {name: 'data_dsc'        , index: 'data_dsc'       , label: "保养项目名称"     , sortable: false  ,width: 300 },
      	    {name: 'u_spec'          , index: 'u_spec'         , label: "上规格"         , sortable: false  ,width: 140 },
      	    {name: 'l_spec'          , index: 'l_spec'         , label: "下规格"         , sortable: false  ,width: 140 },
      	    {name: 'data_typ'        , index: 'data_typ'       , label: "数据类型"        , sortable: false  ,width: 140 },
      	    {name: 'data_cnt'        , index: 'data_cnt'       , label: "样本数量"        , sortable: false  ,width: 120 },
            {name: 'pm_note'        , index: 'pm_note'       , label: "保养描述"        , sortable: false  ,width: 150 }
      	];
      	domObj.grids.$pmItemListGrd.jqGrid({
      		  url:"",
      	      datatype:"local",
      	      mtype:"POST",
      	      autowidth:true,//宽度根据父元素自适应
      	      shrinkToFit:false,
      	      scroll:false,
      	      resizable : true,
      	      loadonce:true,
      	      fixed: true,
      	      viewrecords : true, //显示总记录数
      	      pager : '#pmItemListPg',
      	      rownumbers  :true ,//显示行号
      	      pginput  : false ,
      	      rownumWidth : 20,  //行号列宽度
      	      emptyrecords :true ,
      	      colModel: measureItemListInfoCM
      	});
    }
    
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        controlsFunc.iniDateTimePicker1();
        controlsFunc.iniBayInfo();
    	controlsFunc.resizeFunc();
    	controlsFunc.iniToolRunModeFunc();
    	controlsFunc.iniToolIdFunc();
    	controlsFunc.iniPmTypeFunc();
    	controlsFunc.initLineListFnc();
    	controlsFunc.initShiftIdSel();
    	controlsFunc.initTechConfirmFlg();
    	controlsFunc.initProdConfirmFlg();
    };
    
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
    	domObj.buttons.$query_btn.click(function(){
    		btnFunc.queryFunc();
    	});
    	
    	domObj.buttons.$add_btn.click(function(){
    		btnFunc.addFunc();
    	});
    	
    	domObj.buttons.$PMPlanDialog_addBtn.click(function(){
        	controlsFunc.iniItemDialogFunc("A");
    	});

        domObj.buttons.$import_btn.click(function(){
            btnFunc.selectFileFunc();
        });

        domObj.buttons.$select_btn.change(function() {
            btnFunc.uploadFnc(this);
        });

        domObj.buttons.$download_btn.click(function(){
            btnFunc.downloadTempFun();
        });

        domObj.buttons.$save_btn.click(function(){
			btnFunc.saveExcelFunc();
		});


    };
    
    /**
     * Other action bind
     */
    var otherActionBind = function(){
	    $("form").submit(function(){
	        return false;
	    });
	    
	    domObj.W.resize(function() {
	    	controlsFunc.resizeFunc();
    	});
	    
	    domObj.$toolRunModeSel.change(function(){
	    	controlsFunc.iniToolIdFunc();
	    	controlsFunc.iniPmTypeFunc();
	    });
	    
	    domObj.$toolIdSel.change(function(){
	    	controlsFunc.iniPmTypeFunc();
	    });

	    domObj.$PMPlanDialog_toolIdSel.change(function(){
	    	controlsFunc.iniDialogPmTypeFunc();
	    });
	    
	    domObj.$PMPlanDialog_pmTypeSel.change(function(){
	    	btnFunc.dialogQueryItemFunc();
	    });

        $("#PMPlanDialog_lineIdSel").change(function(){
            controlsFunc.iniDialogToolIdFunc()
        });

        domObj.buttons.$export_btn.click(function(){
            btnFunc.exportFunc();
        });
	    // $("#PMPlanDialog_lineIdSel").on("change",controlsFunc.iniDialogToolIdFunc());
	    
		/*domObj.$PMPlanDialog_pmDateDatepicker.datetimepicker().on('changeDate',function(ev) {
			domObj.$PMPlanDialog_pmDateDatepicker.datetimepicker('hide');
			controlsFunc.iniPlanItemFunc();
		});*/
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
    	iniGridInfo();
    	iniContorlData();
    	iniButtonAction();
    	otherActionBind();

    };
    
    initializationFunc();
});